#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <string.h>
#include <math.h>

#define tupleNum	5000*500 * 8

int main(int argc, char ** argv){
	int *gbCol, gbKey;
	int i,j;
	int key,value;

	if(argc != 5){
		printf("./aggBinaryGen colSize colNum keySize distinctKey\n");
		exit(-1);
	}

	int colSize = atoi(argv[1]);
	int colNum = atoi(argv[2]);
	int keySize = atoi(argv[3]);
	int distinct = atoi(argv[4]);

	gbCol = (int *)malloc(sizeof(int) * colNum);

	if(!gbCol){
		printf("failed to allocate memory!");
		exit(-1);
	}

	char buf[128]= {0};
	for(i=0;i<colNum;i++){
		memset(buf,0,sizeof(buf));
		sprintf(buf, "gbTable%d",i);
		gbCol[i] = open(buf,O_WRONLY|O_CREAT);
	}

	memset(buf,0,sizeof(buf));
	sprintf(buf,"gbKey");
	gbKey = open(buf, O_WRONLY|O_CREAT);

// here we don't care the actual value in the projected col

	for(i=0;i<tupleNum * colSize;i++){
		value = i%100;
		for(j=0;j<colNum;j++){
			write(gbCol[j],&value,sizeof(int));
		}
	}

	int *xx = (int *)malloc(sizeof(int)*distinct);
	for(i=0;i<distinct;i++){
		srandom(i*11+101);
		xx[i] = random() %(1024*1024*10);
	}

// write out the key

	for(i=0; i<tupleNum * colSize; i++){
		srandom(i*13+101);
		int pos = random() %distinct ;
		int key = xx[pos]; 
		write(gbKey, &key, sizeof(int));
	}

	for(i=0;i<colNum;i++){
		close(gbCol[i]);
	}

	close(gbKey);

	return 0;
}
